﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DevExpress.Web.ASPxTreeList;


using DAL;
using System.Configuration;
using System.Text.RegularExpressions;
using DevExpress.Web.ASPxEditors;

using System.Web.Script.Services;
using System.Web.Services;
public partial class BasicInfo_DepartmentInfo : System.Web.UI.Page
{
    public static string ParentID = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        tvShow();
        if (!IsPostBack)
        {
            string ID = ((System.Data.DataRowView)(DXTreelist.FocusedNode.DataItem)).Row.ItemArray[0].ToString();
            if (ParentID == "")
            {
                ParentID = ID;
            }
        }

    }
    // 将数据绑定到treeview中
    private void tvShow()
    {
        DataTable dt = Frame.Global.GlobalSqlHelper.ExecuteSQLToDataTable("select * from css_department order by bmbm");
        this.DXTreelist.DataSource = dt;
        this.DXTreelist.DataBind();
    }
    /// <summary>
    /// 判断输入的编号是否符合规范
    /// </summary>
    /// <param name="Parentid">父级编号</param>
    /// <param name="PartNum">当前输入的部门编号</param>
    /// <returns></returns>
    protected string CheckPartCode(string PartNum)
    {
        string message = "";
        Regex num = new Regex(@"^[0-9]{2}$");
        if (!num.IsMatch(PartNum))
        {
            message = "输入的部门编号格式不正确！<编号必须为两位数字>";
        }
        else
        {
            message = "true";
        }
        return message;
    }
    //添加节点
    protected void DXTreelist_NodeInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        string nowdate = DateTime.Now.ToShortDateString(); //当前编辑的时间
        string txtbmbm = e.NewValues[0].ToString();
        string CurrentBmbm = ParentID + e.NewValues[0].ToString();
        string message = CheckPartCode(txtbmbm);
        try
        {
            if (message == "true")
            {
                using (DataClassesDataContext lqdb = new DataClassesDataContext())
                {
                    //检查输入的编码是否已经存在
                    var result = lqdb.css_department.FirstOrDefault(o => o.bmbm == CurrentBmbm);
                    if (result == null)
                    {
                        #region 添加一条记录
                        css_department part = new css_department();
                        part.fbmbm = ParentID;
                        part.bmbm = ParentID + e.NewValues["bmbm"].ToString();
                        part.bmmc = e.NewValues["bmmc"].ToString();
                        if (e.NewValues["bmmce"] != null)
                            part.bmmce = e.NewValues["bmmce"].ToString();
                        if (e.NewValues["bmsx"] != null)
                            part.bmsx = e.NewValues["bmsx"].ToString();
                        if (e.NewValues["tel"] != null)
                            part.tel = e.NewValues["tel"].ToString();
                        if (e.NewValues["fax"] != null)
                            part.fax = e.NewValues["fax"].ToString();
                        if (e.NewValues["lxr"] != null)
                            part.lxr = e.NewValues["lxr"].ToString();
                        if (e.NewValues["addr"] != null)
                            part.addr = e.NewValues["addr"].ToString();
                        if (e.NewValues["flag"] != null)
                            part.flag = e.NewValues["flag"].ToString();
                        part.lid = CurrentBmbm.Length / 2;
                        part.founder = CMSUser.Current.ID;
                        part.fdate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                        part.editor = CMSUser.Current.ID;
                        part.edate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                        lqdb.css_department.InsertOnSubmit(part);
                        lqdb.SubmitChanges();
                        #endregion
                    }
                    else
                    {
                        throw new Exception("对不起，部门编码重复，请重新添加！");
                    }

                }

                DXTreelist.CancelEdit();
                e.Cancel = true;
                tvShow();
            }
            else
            {
                throw new Exception(message);
            }

        }
        catch (Exception)
        {
            throw;
        }

    }
    //修改节点
    protected void DXTreelist_NodeUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        string nowdate = DateTime.Now.ToShortDateString(); //当前编辑的时间
        string m = e.NewValues[1].ToString();
        string bmbm = e.Keys[0].ToString();
        try
        {
            using (DataClassesDataContext lqdb = new DataClassesDataContext())
            {
                var part = lqdb.css_department.FirstOrDefault(o => o.bmbm == bmbm);
                part.bmmc = e.NewValues["bmmc"].ToString();
                if (e.NewValues["bmmce"] != null)
                    part.bmmce = e.NewValues["bmmce"].ToString();
                if (e.NewValues["bmsx"] != null)
                    part.bmsx = e.NewValues["bmsx"].ToString();
                if (e.NewValues["tel"] != null)
                    part.tel = e.NewValues["tel"].ToString();
                if (e.NewValues["fax"] != null)
                    part.fax = e.NewValues["fax"].ToString();
                if (e.NewValues["lxr"] != null)
                    part.lxr = e.NewValues["lxr"].ToString();
                if (e.NewValues["addr"] != null)
                    part.addr = e.NewValues["addr"].ToString();
                if (e.NewValues["flag"] != null)
                    part.flag = e.NewValues["flag"].ToString();
                part.editor = CMSUser.Current.ID;// CMSUser.Current.Name;
                part.edate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                lqdb.SubmitChanges();
            }
            DXTreelist.CancelEdit();
            e.Cancel = true;
            tvShow();
        }
        catch (Exception)
        {
            throw;
        }

    }
    //删除节点
    protected void DXTreelist_NodeDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
        string bmbm = e.Keys[0].ToString();
        try
        {
            using (DataClassesDataContext lqdb = new DataClassesDataContext())
            {
                var part = lqdb.css_department.FirstOrDefault(o => o.bmbm == bmbm);
                lqdb.css_department.DeleteOnSubmit(part);
                lqdb.SubmitChanges();
            }
            DXTreelist.CancelEdit();
            e.Cancel = true;
            tvShow();
        }
        catch (Exception)
        {
            throw;
        }

    }
    //callback
    protected void DXTreelist_CustomDataCallback(object sender, TreeListCustomDataCallbackEventArgs e)
    {
        //获取编号
        string key = e.Argument.ToString();
        TreeListNode node = DXTreelist.FindNodeByKeyValue(key);
        string bmmc = node.GetValue("bmmc").ToString();  // 部门名称
        e.Result = bmmc;
        //获取父级编号
        ParentID = key;
        //fbmbms = node.GetValue("bmbm").ToString();
        // lblbmbm.Text = node.GetValue("bmbm").ToString();
        //node.GetValue("bmbm"); 
    }
    //添加以及部门
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string nowdate = DateTime.Now.ToShortDateString(); //当前编辑的时间
        string bmbm = txtbmbm.Text;
        string bmmc = txtbmmc.Text;
        string bmmce = txtbmmce.Text;
        string tel = txttel.Text;
        string fax = txtfax.Text;
        string lxr = txtlxr.Text;
        string addr = txtaddr.Text;
        string bmsx = cmdbmsx.Value.ToString();
        string flag = cmdflag.Value.ToString();
        string message = CheckPartCode(bmbm);
        if (bmbm.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("部门编码不能为空！");
        }
        else if (bmmc.Equals(""))
        {
            Frame.Global.GlobalFunctions.Alert("部门名称不能为空！");
        }
        else
        {

            if (message == "true")
            {
                using (DataClassesDataContext lqdb = new DataClassesDataContext())
                {
                    var result = lqdb.css_department.FirstOrDefault(r => r.bmbm == bmbm);
                    if (result == null)
                    {
                        #region 添加一条记录
                        css_department part = new css_department();
                        part.fbmbm = "0";
                        part.bmbm = bmbm;
                        part.bmmc = bmmc;
                        part.bmmce = bmmce;
                        part.bmsx = bmsx;
                        part.addr = addr;
                        part.lid = bmbm.Length / 2;
                        part.tel = tel;
                        part.fax = fax;
                        part.lxr = lxr;
                        part.flag = flag;

                        part.founder = CMSUser.Current.ID;
                        part.fdate = nowdate;
                        part.editor = CMSUser.Current.ID;
                        part.edate = nowdate;
                        lqdb.css_department.InsertOnSubmit(part);
                        lqdb.SubmitChanges();
                        Frame.Global.GlobalFunctions.Alert("添加成功！");
                        tvShow();
                        //Response.Write("<script language='javascript'> if (popControlYjBm.IsWindowVisible()) { popControlYjBm.Hide();}</script>");
                        
                        #endregion
                    }
                    else
                    {
                        Frame.Global.GlobalFunctions.Alert("部门编号不能重复！");
                    }
                }
            }
            else
            {
                Frame.Global.GlobalFunctions.Alert(message);
            }
        }




    }

    protected void DXTreelist_CellEditorInitialize(object sender, TreeListColumnEditorEventArgs e)
    {
        if (e.Column.FieldName == "bmmc")
        {
            e.Editor.Focus();
        }
        e.Editor.SetClientSideEventHandler("KeyPress", @"function(s,e){var key = event.keyCode;if(key==13){EnterAsTab();}}");
    }

    //ajax客户端获取数据
    [WebMethod]
    public static string[] GetUsers(string bmbm)
    {
        using (DataClassesDataContext context = new DataClassesDataContext())
        {
            var us = context.css_department_rybm.Where(u => u.bmbm.Trim() == bmbm.Trim()).Select(u => u.rybm).ToArray();
            return us;
        }
    }
    //保存部门负责人
    protected void gvUserList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Parameters))
        {
            List<string> IDlist = gvUserList.GetSelectedFieldValues("rybm").Select<object, string>(o => o.ToString()).ToList();
            using (DataClassesDataContext lqdb = new DataClassesDataContext())
            {
                foreach (var item in IDlist)
                {
                    css_department_rybm de = lqdb.css_department_rybm.FirstOrDefault(o => o.bmbm == e.Parameters && o.rybm == item.Trim());
                    if (de == null)
                    {
                        de = new css_department_rybm();
                        de.bmbm = e.Parameters;
                        de.rybm = item.Trim();
                        lqdb.css_department_rybm.InsertOnSubmit(de);
                    }
                }
                lqdb.SubmitChanges();
            }
        }
        // pupControl.Attributes.Add("Click", "pupControl.Hide();");
    }

    protected void pupYj_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        tvShow();
    }
}